package com.golddaymicromall.activity.salemanager;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.activity.setting.personal.address.AddressChoiceActivity;
import com.golddaymicromall.adapter.FirstPurchaseConfirmPayAdapter;
import com.golddaymicromall.adapter.GiftAdapter;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.ActiveInfo;
import com.golddaymicromall.bean.ActiveProInfo;
import com.golddaymicromall.bean.AddressInfo;
import com.golddaymicromall.bean.ProductInfo;
import com.golddaymicromall.util.MD5;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class FirstPurchaseConfirmActivity extends BaseActivity implements ListView.OnClickListener {

    private List<ProductInfo> list;
    private List<AddressInfo> listAddress = new ArrayList<AddressInfo>();
    public static final int REQUSET = 1;
    private String addressid;
    float RealPay; //实付价
    private FirstPurchaseConfirmPayAdapter adapter;
    String customerId;
    String productId;
    private float AllPrice;


    private TextView mAllPrice;
    private ListView mLv;
    private LinearLayout mConfirmPayBack;
    private LinearLayout mConfirmPay_ChangeAddress;
    private TextView mUsername;
    private TextView mAddress;
    private TextView mPhone;
    private TextView mConfirmPayment;
    private TextView mConfirmAddCart;

    List<ActiveInfo> activeInfos = new ArrayList<ActiveInfo>();
    List<ActiveProInfo> activeProInfos = new ArrayList<ActiveProInfo>();

    List<ActiveProInfo> activeProInfosAdapter;

    GiftAdapter giftAdapter;
    ListView mGiftlv;
    TextView mGiftText;
    int activeFlag = 1;
    String mDeptFlag;

    //接收返回的值
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConfirmPayActivity.REQUSET && resultCode == RESULT_OK) {
            addressid = data.getStringExtra("id");
            String nameAddress = data.getStringExtra("name_address");
            String address = data.getStringExtra("address");
            String phone = data.getStringExtra("phone");
            mUsername.setText("收货人：" + nameAddress);
            mPhone.setText(phone);
            mAddress.setText("地址：" + address);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_purchase_confirm);
        SPUtils.put(FirstPurchaseConfirmActivity.this, "saleflag", "1");
        customerId = SPUtils.get(getApplicationContext(), "Id", "").toString();
        mDeptFlag = SPUtils.get(getApplicationContext(), "deptFlag", "").toString();
        list = (List<ProductInfo>) getIntent().getSerializableExtra("listFlag");
        initView();
        attemptAddress();
    }

    private void initView() {
        mLv = (ListView) findViewById(R.id.secondpurchase_listview);
        mAllPrice = (TextView) findViewById(R.id.allPrice);
        mConfirmPayBack = (LinearLayout) findViewById(R.id.confirmpay_back);
        mConfirmPay_ChangeAddress = (LinearLayout) findViewById(R.id.confirmPay_changeAddress);
        mUsername = (TextView) findViewById(R.id.confirmPay_username);
        mAddress = (TextView) findViewById(R.id.confirmPay_address);
        mPhone = (TextView) findViewById(R.id.confirmPay_phone);
        mConfirmPayment = (TextView) findViewById(R.id.confirmpayment);
        mConfirmAddCart = (TextView) findViewById(R.id.confirmAddcart);
        mGiftText = (TextView) findViewById(R.id.gift_text);
        mGiftlv = (ListView) findViewById(R.id.gift_listview);
        mConfirmAddCart.setOnClickListener(this);
        mConfirmPayment.setOnClickListener(this);
        mConfirmPayBack.setOnClickListener(this);
        mConfirmPay_ChangeAddress.setOnClickListener(this);
        adapter = new FirstPurchaseConfirmPayAdapter(list, FirstPurchaseConfirmActivity.this);
        mLv.setAdapter(adapter);
        AllPrice = Float.valueOf(list.get(0).getPrice());
        RealPay = Float.valueOf(list.get(0).getPv());
        productId = list.get(0).getId();
        mAllPrice.setText(AllPrice + "");
        mConfirmPayment.setText("确认结算（" + RealPay + ")");
        mAddress.setText("您还没有默认收货地址，请到个人设置中设置地址");
        String secondAct = SPUtils.get(getApplicationContext(), "secondAct", "").toString();
        String secondActPro = SPUtils.get(getApplicationContext(), "secondActPro", "").toString();
        if (!"0".equals(secondAct)) {
            activeInfos = JSON.parseArray(secondAct, ActiveInfo.class);
        }
        if (!"0".equals(secondActPro)) {
            activeProInfos = JSON.parseArray(secondActPro, ActiveProInfo.class);
        }
        if (!"0".equals(SPUtils.get(getApplicationContext(), "secondAct", "").toString())) {
            activeProInfosAdapter = new ArrayList<ActiveProInfo>();
            if (activeInfos.size() == 1) {
                activeFlag = 1;
                mGiftText.setVisibility(View.VISIBLE);
                for (int i = 0; i < activeProInfos.size(); i++) {
                    if (activeInfos.get(0).getId().equals(activeProInfos.get(i).getActiveid())) {
                        //创建赠品适配器
                        activeProInfosAdapter.add(activeProInfos.get(i));
                        mGiftText.setText("赠品：价值 ￥" + activeInfos.get(0).getPrice());
                    }
                }
                if (activeProInfosAdapter != null) {
                    giftAdapter = new GiftAdapter(activeProInfosAdapter, FirstPurchaseConfirmActivity.this, activeFlag);
                    mGiftlv.setAdapter(giftAdapter);
                    if (activeProInfosAdapter.size() == 0) {
                        mGiftText.setVisibility(View.GONE);
                    }
                } else {
                    mGiftText.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirmpay_back:
                finish();
                break;
            case R.id.confirmPay_changeAddress:
                Intent intent2choiceaddress = new Intent(this, AddressChoiceActivity.class);
                startActivityForResult(intent2choiceaddress, REQUSET);
                break;
            case R.id.confirmpayment:




                if (mAddress.getText().toString().contains("没有")) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    attemptCreateOrder("1");
                }

                break;
            case R.id.confirmAddcart:
                if (mAddress.getText().toString().contains("没有")) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    attemptCreateOrder("2");
                }
                break;
        }
    }

    //添加购物车
    private void attemptCreateOrder(String flag) {
        if (mAddress.getText().toString().contains("没有")) {
            Toast.makeText(this, "请选择地址", Toast.LENGTH_SHORT).show();
            return;
        }
        mConfirmPayment.setEnabled(false);

        MD5 md = new MD5();
        String md5Realpayment = md.toMD5(String.valueOf(RealPay));
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.createorder");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("productId", productId);
        form.put("adressid", addressid);
        form.put("customerid", customerId);
        form.put("orderType", "1");
        form.put("orderClass", "1");
        form.put("orderPrice", String.valueOf(AllPrice)); //总价
        form.put("orderRealpayment", String.valueOf(RealPay)); //实付价
        form.put("orderAllpv", String.valueOf(RealPay)); //pv
        form.put("orderRealpv", String.valueOf(RealPay)); //pv
        form.put("md5Realpayment", md5Realpayment);//加密
        form.put("flag", mDeptFlag);
        form.put("orderName", "A");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> {
                    mConfirmPayment.setEnabled(false);
                    FirstPurchaseConfirmActivity.this.showLoading();
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();

                    if (!"".equals(result)) {
                        if ("0".equals(result)) {
                            mConfirmPayment.setEnabled(true);
                            Toast.makeText(FirstPurchaseConfirmActivity.this, "确认结算失败，请重新提交", Toast.LENGTH_SHORT).show();
                        } else if ("3".equals(result)) {
                            mConfirmPayment.setEnabled(true);
                            Toast.makeText(FirstPurchaseConfirmActivity.this, "您已经进行过首次进货，不能重复购买", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            mConfirmPayment.setEnabled(true);
                            if ("1".equals(flag)) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(FirstPurchaseConfirmActivity.this);
                                builder.setMessage("订单已提交到销售管理页面！\n点击“确定”继续支付，\n点击“取消”返回继续购买");
                                builder.setTitle("提示");
                                builder.setPositiveButton("确定", (dialog2, which) -> {
                                    dialog2.dismiss();
                                    //设置你的操作事项
                                    Intent intent2PayPwd = new Intent(FirstPurchaseConfirmActivity.this, ConfirmPayPwdActivity.class);
                                    intent2PayPwd.putExtra("orderId", result);
                                    startActivity(intent2PayPwd);
                                    MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                                            SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "首次进货，创建订单,订单编号：" + result + ",价格：" + RealPay + ",赠品" + mGiftText.getText());
                                    finish();
                                });

                                builder.setNegativeButton("取消",
                                        (dialog3, which) -> {
                                            dialog3.dismiss();
                                            finish();
                                        });
                                builder.create().show();
                            } else if ("2".equals(flag)) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(FirstPurchaseConfirmActivity.this);
                                builder.setMessage("订单已提交到销售管理页面！\n请返回查看");
                                builder.setTitle("提示");
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                                                SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "首次进货，添加购物车,订单编号：" + result + ",价格：" + RealPay + ",赠品" + mGiftText.getText());
                                        dialog.dismiss();
                                        finish();
                                    }
                                });
                                builder.create().show();
                            }
                            mConfirmPayment.setEnabled(true);
                        }
                    }
                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    //获取默认地址
    public void attemptAddress() {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerId", customerId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(FirstPurchaseConfirmActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
//                            Toast.makeText(FirstPurchaseConfirmActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                            mAddress.setText("您还没有收货地址，请到个人设置中添加");
                        } else {
                            listAddress = JSON.parseArray(result, AddressInfo.class);
                            for (int i = 0; i < listAddress.size(); i++) {
                                if ("1".equals(listAddress.get(i).getAddress_default())) {
                                    addressid = listAddress.get(i).getId();
                                    mUsername.setText("收货人：" + listAddress.get(i).getReceivername());
                                    mPhone.setText(listAddress.get(i).getPhone());
                                    mAddress.setText("地址：" + listAddress.get(i).getCountryname()
                                            + listAddress.get(i).getProvincename() + listAddress.get(i).getCityname()
                                            + listAddress.get(i).getAreaname() + listAddress.get(i).getStreet());
                                }
                            }
                        }
                    } else {
                        //在获取不到数据时的处理
                        mAddress.setText("您还没有收货地址，请到个人设置中设置地址");
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
